package com.example.sens.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.example.sens.entity.Conclusion;
import com.example.sens.entity.Performance;
import com.example.sens.entity.Quiz;
import com.example.sens.entity.User;
import com.example.sens.mapper.ConclusionMapper;
import com.example.sens.mapper.PerformanceMapper;
import com.example.sens.mapper.QuizMapper;
import com.example.sens.mapper.UserMapper;
import com.example.sens.service.PerformanceService;
import com.example.sens.utils.Response;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PerformanceServiceImpl implements PerformanceService{

    @Resource
    private PerformanceMapper performanceMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private QuizMapper quizMapper;
    @Resource
    private ConclusionMapper conclusionMapper;
    @Override
    public Page<Performance> findAll(Page page) {
        List<Performance> list = performanceMapper.getByPage(page);
        List<Long> userIds = list.stream().map(p -> p.getUserId()).collect(Collectors.toList());
        List<User> users = userMapper.selectByUserIds(userIds);
        List<Long> quizIds = list.stream().map(p -> p.getQuizId()).collect(Collectors.toList());
        List<Quiz> quizList = quizMapper.selectByQuizIds(quizIds);
        List<Conclusion> conclusionList = conclusionMapper.findByQuizIds(quizIds);
        list.stream().forEach(t -> {
            User user = users.stream().filter(p -> p.getUserId().equals(t.getUserId())).findFirst().orElse(new User());
            t.setUsername(user.getUserName());
            Quiz quiz = quizList.stream().filter(p -> p.getId().equals(t.getQuizId())).findFirst().orElse(new Quiz());
            t.setQuizTitle(quiz.getTitle());
            Conclusion conclusion = conclusionList.stream().filter(p -> p.getQuizId().equals(t.getQuizId()) && t.getUserId().equals(p.getUserId())).findFirst().orElse(new Conclusion());

        });
        return page.setRecords(list);
    }

    @Override
    public Response updateScore(Performance performance) {
        int effect = performanceMapper.updateByPrimaryKeySelective(performance);
        if(effect < 1) {
            return Response.no("插入失败");
        }
        return Response.yes();
    }
}
